#include "aerPath.hpp"


#ifdef AER_WINDOWS
# include <direct.h>
# define AER_GETPWD()   _getcwd( NULL, 0)
#else
# include <unistd.h>
# define AER_GETPWD()   getcwd( NULL, 0)
#endif

#define DIR_SEPARATOR   '/'



namespace aer {

void Path::CleanFilename(std::string &filename)
{
  size_t pos;
  
  // replaces Windows' antislash by Unix' slash
  while ((pos=filename.find_first_of('\\')) != std::string::npos) {
    filename.replace( pos, 1u, 1u, DIR_SEPARATOR );
  }
  
  // clean previous dir marker
  while ((pos=filename.find("..")) != std::string::npos)
  {
    if (pos <= 1) {
      filename.replace( 0, pos+3, 1, DIR_SEPARATOR);
      continue;
    }
    
    size_t prev_dir = filename.find_last_of( DIR_SEPARATOR, pos-2) + 1;
    filename.erase( prev_dir, (pos-prev_dir)+3 );
  } 
  
  // clean current dir marker
  while ((pos=filename.find("./")) != std::string::npos) {    
    filename.erase( pos, 2 );
  } 
}




Path::Path(const char *pathname)
  : m_nameIdx(0u)
{
  char *cwd = AER_GETPWD();
  m_canonical = cwd;
  m_canonical += DIR_SEPARATOR;
  changeDirectory( pathname );  
  AER_SAFE_FREE( cwd );
}

Path::Path(const Path &path)
  : m_canonical(path.m_canonical),
    m_nameIdx(path.m_nameIdx)
{ 
}


void Path::changeDirectory(const char *path)
{
  AER_CHECK( path != NULL );  
  
  if (path[0] == DIR_SEPARATOR) {
    m_canonical = std::string( path );
  } else {
    m_canonical += path;
  }
  
  CleanFilename( m_canonical );   
  
  // Name index
  if (isDirectory()) {
    m_nameIdx = m_canonical.find_last_of(DIR_SEPARATOR, m_canonical.length()-2) + 1;  
  } else {
    m_nameIdx = m_canonical.find_last_of(DIR_SEPARATOR) + 1;  
  }
  
  m_canonicalDirectory = m_canonical.substr( 0, m_nameIdx);//
}

const char* Path::getName() const
{
  return &(m_canonical.c_str()[m_nameIdx]);
}

const char* Path::getDirectory() const
{
  return m_canonicalDirectory.c_str();
}

const char* Path::getCanonical() const
{
  return m_canonical.c_str();
}

bool Path::isDirectory() const {
  return m_canonical.at(m_canonical.length()-1) == DIR_SEPARATOR;
}

} // aer

